<template>
  <div id="login">
    <div class="form">
      <div class="title"></div>
      <div class="main">
        <el-form :rules="rules" :model="formDate" ref="formRef">
          <el-form-item prop="username">
            <el-input v-model="formDate.username" placeholder="请输入用户名" @keyup.native.enter="login"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="formDate.password"
              placeholder="请输入密码"
              type="password"
              showPassword
              @keyup.native.enter="login"
            ></el-input>
          </el-form-item>
          <el-button type="primary" size="small" @click="login">登录</el-button>
          <el-form-item>
            <el-link :underline="false" @click="$router.replace('/register')">去注册</el-link>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { loginAPI } from '@/api/Login.js'
export default {
  name: 'Login',
  data() {
    return {
      // 表单的双向绑定数据
      formDate: {
        username: '',
        password: ''
      },
      // 表单的验证规则
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { pattern: /^[1-9a-zA-Z]{2,10}$/, message: '用户名必须是2-10的字母数字', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码必须是6-15的非空字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 登录按钮的事件
    login() {
      // 兜底校验
      this.$refs.formRef.validate(async valid => {
        if (!valid) return
        const {
          data: { code, message, token }
        } = await loginAPI(this.formDate)
        // 不成功,给错误提示
        if (code !== 0) return this.$message.error(message)
        // 成功给提示
        this.$message.success(message)
        // 清空表单数据
        this.$refs.formRef.resetFields()
        // 存储token
        this.$store.commit('userModule/setToken', token)
        // 跳转至首页
        this.$router.replace('/')
      })
    }
  }
}
</script>

<style lang="less" scoped>
#login {
  height: 100%;
  background: url('../../assets/images/login_bg.jpg') no-repeat center;
  background-size: cover;
  .form {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 400px;
    height: 300px;
    background-color: #fff;
    border-radius: 15px;
    padding: 0 30px;
    box-sizing: border-box;
    .title {
      height: 60px;
      background: url('../../assets/images/login_title.png') no-repeat center;
    }
    .el-button {
      width: 100%;
    }
  }
}
</style>
